{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "20\n",
      "40\n",
      "60\n",
      "80\n",
      "100\n",
      "120\n",
      "140\n",
      "160\n",
      "180\n",
      "200\n",
      "220\n",
      "240\n",
      "260\n",
      "280\n",
      "300\n",
      "320\n",
      "340\n",
      "360\n",
      "380\n",
      "400\n",
      "420\n",
      "440\n",
      "460\n",
      "480\n",
      "500\n",
      "520\n",
      "540\n",
      "560\n",
      "580\n",
      "600\n",
      "620\n",
      "640\n",
      "660\n",
      "680\n",
      "700\n",
      "720\n",
      "740\n",
      "760\n",
      "780\n",
      "800\n",
      "820\n",
      "840\n",
      "860\n",
      "880\n",
      "900\n",
      "920\n",
      "940\n",
      "960\n",
      "980\n",
      "1000\n"
     ]
    }
   ],
   "source": [
    "num = 0\n",
    "for i in range(1,51):\n",
    "    r = requests.get('http://www.alexa.cn/siterank/' + str(i))\n",
    "    soup = BeautifulSoup(r.text, \"lxml\")\n",
    "    span_list = soup.find_all('span', class_ = 'domain-link')   \n",
    "    link_list = [(str(j + num), span_list[j].a['href']) for j in range(len(span_list))]\n",
    "    num = num + len(link_list)\n",
    "        \n",
    "    output = \"\\n\".join(\"%s\\t%s\" % tup for tup in link_list) + \"\\n\"\n",
    "    print (num)\n",
    "    with open('C:\\\\Users\\\\Administrator\\\\Desktop\\\\alexa.txt', 'a+', encoding = 'utf-8') as f:\n",
    "        f.write(output)\n",
    "        f.close\n",
    "    time.sleep(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
